package dao

import (
	"errors"
	"github.com/google/uuid"
	__ "goods_srv/basic/goodsrpc"
	"goods_srv/handler/models"
	"time"
)

// 商品运费
func CalculateShippingFee(weight float64, wayLong float64) float64 {
	var baseFee float64 = 5
	var weightFee float64
	var wayLongFee float64

	switch {
	case weight < 2.0:
		weightFee = 2
	case weight >= 2 && weight < 10:
		weightFee = 2.0 + weight - 2*0.8
	case weight >= 10:
		weightFee = 2.0 + 8*0.8 + weight - 10*1
	}
	switch {
	case wayLong < 5:
		wayLongFee = 5
	case wayLong >= 5 && wayLong < 15:
		wayLongFee = 5 + wayLong - 5*0.5
	case wayLong > 15:
		wayLongFee = 5 + 10*0.5 + wayLong - 15*0.7
	}

	shippingFee := weightFee + wayLongFee + baseFee

	return shippingFee
}

// 创建订单
func CreateOrder(in *__.CreateGoodsOrderReq) (models.GoodsOrder, error) {
	var g models.Goods
	g.Id = in.GoodsId
	if err := g.GetGoodsById(); err != nil {
		return models.GoodsOrder{}, errors.New("获取商品信息失败")
	}
	if int32(g.GoodsStock) < in.Num {
		return models.GoodsOrder{}, errors.New("库存不足")
	}
	// 2. 创建订单
	order := models.GoodsOrder{
		OrderNo:     "JD" + time.Now().Format("20060102150405") + uuid.NewString()[:8],
		AddressId:   in.AddressId,
		UserId:      in.UserId,
		GoodId:      in.GoodsId,
		GoodsNum:    in.Num,
		GoodsName:   g.GoodsName,
		GoodsPrice:  int64(g.GoodsPrice),
		OrderPrice:  g.GoodsPrice * float64(in.Num),
		OrderStatus: 1,
	}

	// 3. 保存订单
	err := order.Create()
	if err != nil {
		return models.GoodsOrder{}, err
	}
	return order, nil
}

// 发货
func BatchShipping(in *__.BatchShippingReq) error {

	var o models.GoodsOrder
	o.Id = in.OrderId
	if err := o.GetOrderById(); err != nil {
		return errors.New("获取订单信息失败" + err.Error())
	}
	if o.ShopId != int32(in.ShopId) {
		return errors.New("店铺id不一致")
	}
	if o.OrderStatus != 2 {
		return errors.New("订单状态错误")
	}
	o.OrderStatus = 3
	if err := o.Update(); err != nil {
		return errors.New("发货失败" + err.Error())
	}
	return nil
}

// 商品详情
func GoodsDetail(id int32) (models.Goods, error) {
	var g models.Goods
	g.Id = id
	if err := g.GetGoodsById(); err != nil {
		return models.Goods{}, errors.New("获取商品信息失败" + err.Error())
	}
	return g, nil
}

// 订单详情
func OrderDetail(id uint64) (models.OrderDetailResp, error) {
	var o models.GoodsOrder
	o.Id = id
	res, err := o.GetOrderDetail()
	if err != nil {
		return models.OrderDetailResp{}, errors.New("获取订单信息失败:" + err.Error())
	}
	return res, nil
}
